package com.sxyjhh.fg.service;


import com.sxyjhh.dbutil.basic.ConstConfig;
import com.sxyjhh.dbutil.basic.DBQueryUtils;
import com.sxyjhh.dbutil.utils.DBInfoUtil;
import com.sxyjhh.fg.dao.*;
import com.sxyjhh.fg.model.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.sxyjhh.dbutil.utils.CommonUtils.YYYYMMDD;
import static com.sxyjhh.dbutil.utils.CommonUtils.YYYYMMDDHHMMSS;

@Service
public class CreditSaveDataService {
    private static final Logger logger = LoggerFactory.getLogger(CreditSaveDataService.class);

    @Value("${output.datasource.ip}")
    private String ip;

    @Value("${output.datasource.db.name}")
    private String dbName;

    @Value("${output.datasource.username}")
    private String username;

    @Value("${output.datasource.password}")
    private String password;

    @Value("${output.datasource.port}")
    private String port;

    @Value("${output.datasource.type}")
    private String dType;
    @Autowired
    private KcsjQysxRepository kcsjQysxRepository;
    @Autowired
    private QyXkxxRepository qyXkxxRepository;
    @Autowired
    private YthQysxRepository ythQysxRepository;

    @Autowired
    private YthJlsxRepository ythJlsxRepository;
    @Autowired
    private KcsjJlsxRepository kcsjJlsxRepository;

    public boolean saveData(String ythType, String dataArray, String tableName) throws ParseException {

        if (StringUtils.isBlank(dataArray)) {
            return false;
        }
        logger.info("receive data :" + ythType);

        if ("yth_qy".equals(ythType) || "kc_qy".equals(ythType) ||
                "yjl_xy".equals(ythType) || "kc_jl".equals(ythType)
                || "yth_jl".equals(ythType)) {

            jpaSaveData(ythType, dataArray);
        } else {
            JSONArray jsonArray = JSONArray.fromObject(dataArray);

            List<Map<String, Object>> resList = getResList(jsonArray, ythType);

            ConstConfig.DBType dbType = ConstConfig.DBType.valueOf(Integer.valueOf(dType));
            String url = DBInfoUtil.getDBUrl(dbType, ip, port, dbName);
            DBQueryUtils dbQueryUtils = new DBQueryUtils(DBInfoUtil.getDBDriverName(dbType),
                    url, username, password, 5);

            try {
                dbQueryUtils.insertBatchData(tableName, dbName, resList);
            } catch (SQLException e) {
                logger.error("creditSaveData", e);
                //System.out.println("creditSaveData:=========================" + e.getMessage());
                //method1("creditSaveData:=========================" + e);
                return false;
            }

        }
        return true;
    }

    //转换数据类型
    private List<Map<String, Object>> getResList(JSONArray enterArray, String ythType) {
        List<Map<String, Object>> resList = new ArrayList<>();
        for (int i = 0; i < enterArray.size(); i++) {
            JSONObject json = JSONObject.fromObject(enterArray.get(i));
            json = filterNull(json);

            Map<String, Object> classItem = (Map<String, Object>) json;
            if ("yth_qy".equals(ythType)) {
                classItem.remove("CREATEDATE");
            }

            resList.add(classItem);
        }
        return resList;
    }

    public static JSONObject filterNull(JSONObject jsonObj) {
        Iterator<String> it = jsonObj.keys();
        Object obj = null;
        String key = null;
        while (it.hasNext()) {
            key = it.next();
            obj = jsonObj.get(key);
            if (obj instanceof JSONObject) {
                filterNull((JSONObject) obj);
            }
            if (obj instanceof JSONArray) {
                JSONArray objArr = (JSONArray) obj;
                for (int i = 0; i < objArr.size(); i++) {
                    filterNull(objArr.getJSONObject(i));
                }
            }
            if (obj == null || obj instanceof JSONNull) {
                jsonObj.put(key, "");
            }
            if (obj.equals(null)) {
                jsonObj.put(key, "");
            }
        }
        return jsonObj;
    }

    public boolean delData(String tableName) {
        ConstConfig.DBType dbType = ConstConfig.DBType.valueOf(Integer.valueOf(dType));
        String url = DBInfoUtil.getDBUrl(dbType, ip, port, dbName);
        DBQueryUtils dbQueryUtils = new DBQueryUtils(DBInfoUtil.getDBDriverName(dbType),
                url, username, password, 5);

        boolean flag = false;
        try {
            flag = dbQueryUtils.execDDLSql("delete from " + tableName);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    private boolean jpaSaveData(String ythType, String dataArray) throws ParseException {
        JSONArray jsonArray = JSONArray.fromObject(dataArray);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = JSONObject.fromObject(jsonArray.get(i));
            if ("yth_qy".equals(ythType)) {
                YthQysx ythQysx = new YthQysx(json.get("ID") + "",
                        json.get("ENNAME") + "",
                        json.get("FILECODE") + "",
                        json.get("HAPPENTIME") + "",
                        json.get("PRONAME") + "",
                        json.get("PROLOCA") + "",
                        json.get("PROCITY") + "",
                        json.get("PROAREA") + "",
                        json.get("SERIALNUMBER") + "",
                        json.get("ACTIVEDES") + "",
                        json.get("ACTIVECODE") + "",
                        json.get("SCORE") + "",
                        json.get("BEHAVIORDESC") + "",
                        json.get("GOOGBADDIST") + "",
                        json.get("AWARDEDDEPARTMENT") + "",
                        json.get("AWARDEDTIME") + "",
                        json.get("RECORDDEPARTMENT") + "",
                        json.get("RELEASEDATE") + "",
                        json.get("AWARDEDCONTENT") + "",
                        json.get("AWARDEDID") + "",
                        json.get("CREATETIME") + "",
                        json.get("CORPCODE") + "",
                        json.get("CREATEUSERNAME") + "",
                        json.get("FREGIONNO") + "",
                        json.get("DEPARTLEVEL") + "",
                        json.get("PUNISHEVIDENCE") + "",
                        json.get("FPUNISHEDATE") + "",
                        json.get("PRJNUM") + "",
                        json.get("BUILDCORPNAME") + "",
                        json.get("BUILDCORPCODE") + "",
                        json.get("PROVINCENUM") + "",
                        json.get("CITYNUM") + "",
                        json.get("COUNTYNUM") + "",
                        json.get("CREDITCLASSNUM") + "",
                        json.get("PUNISHMONEY") + "",
                        YYYYMMDDHHMMSS.parse(json.get("UPDATETIME") + ""));
                ythQysxRepository.save(ythQysx);
            }
            if ("yjl_xy".equals(ythType)) {
                QyXkxx qyXkxx = new QyXkxx(json.get("id") + "",
                        json.get("xy010101") + "",
                        json.get("xy010133") + "",
                        json.get("xy010102") + "",
                        json.get("xy010501") + "",
                        json.get("xy010701") + "",
                        json.get("xy010105") + "",
                        json.get("xy010108") + "",
                        json.get("xy010301") + "",
                        json.get("xy010302") + "",
                        json.get("xy010311") + "",
                        json.get("xy010323") + "",
                        json.get("xy010324") + "",
                        json.get("xy010303") + "",
                        YYYYMMDDHHMMSS.parse(json.get("xy010305") + ""),
                        YYYYMMDDHHMMSS.parse(json.get("xy010325") + ""),
                        YYYYMMDDHHMMSS.parse(json.get("xy010306") + ""),
                        json.get("xy010307") + "",
                        json.get("xy010326") + "",
                        json.get("xy010308") + "",
                        json.get("xy010327") + "",
                        json.get("xy010328") + "",
                        json.get("xy010310") + "",
                        YYYYMMDDHHMMSS.parse(json.get("create_time") + ""),
                        YYYYMMDDHHMMSS.parse(json.get("update_time") + ""));
                qyXkxxRepository.save(qyXkxx);
            }
            if ("kc_qy".equals(ythType)) {
                KcsjQysx kcsjQysx = new KcsjQysx(json.get("ID") + "",
                        json.get("ENNAME") + "",
                        json.get("FILECODE") + "",
                        json.get("HAPPENNTIME") + "",
                        json.get("PRONAME") + "",
                        json.get("PROLOCA") + "",
                        json.get("PROCITY") + "",
                        json.get("PROAREA") + "",
                        json.get("SERIALNUMBER") + "",
                        json.get("ACTIVEDES") + "",
                        json.get("ACTIVECODE") + "",
                        json.get("SCORE") + "",
                        json.get("BEHAVIORDESC") + "",
                        json.get("GOOGBADDIST") + "",
                        json.get("AWARDEDDEPARTMENT") + "",
                        json.get("AWARDEDTIME") + "",
                        json.get("RECORDDEPARTMENT") + "",
                        json.get("RELEASEDATE") + "",
                        json.get("AWARDEDCONTENT") + "",
                        json.get("AWARDEDID") + "",
                        json.get("CREATETIME") + "",
                        json.get("CORPCODE") + "",
                        json.get("CREATEUSERNAME") + "",
                        json.get("FREGIONNO") + "",
                        json.get("DEPARTLEVEL") + "",
                        json.get("PUNISHEVIDENCE") + "",
                        json.get("FPUNISHEDATE") + "",
                        json.get("PRJNUM") + "",
                        json.get("BUILDCORPNAME") + "",
                        json.get("BUILDCORPCODE") + "",
                        json.get("PROVINCENUM") + "",
                        json.get("CITYNUM") + "",
                        json.get("COUNTYNUM") + "",
                        json.get("CREDITCLASSNUM") + "",
                        json.get("PUNISHMONEY") + "",
                        YYYYMMDD.parse(json.get("UPDATETIME") + ""));

                kcsjQysxRepository.save(kcsjQysx);
            }
            if ("yth_jl".equals(ythType)) {
                YthJlsx ythJlsx = new YthJlsx(json.get("ID") + "",
                        json.get("NAME") + "",
                        json.get("CARDCODE") + "",
                        json.get("REGISTCODE") + "",
                        json.get("PRJNAME") + "",
                        json.get("ILLEGALTIME") + "",
                        json.get("ILLVALIDTERM") + "",
                        json.get("ILLEGALCODE") + "",
                        json.get("ILLEGALBEHAVIOR") + "",
                        json.get("ILLEGALSCORE") + "",
                        json.get("SCOREST") + "",
                        json.get("SCOREET") + "",
                        json.get("OPERATETIME") + "",
                        json.get("NUMSALL") + "",
                        json.get("SCOREALL") + "",
                        json.get("FIGUREPROBAR") + "",
                        json.get("SAFECHECODE") + "",
                        json.get("SUBMITSTATUS") + "",
                        json.get("ORGID") + "",
                        YYYYMMDDHHMMSS.parse(json.get("UPDATETIME") + ""));
                ythJlsxRepository.save(ythJlsx);
            }
            if ("kc_jl".equals(ythType)) {
                KcsjJlsx kcsjJlsx = new KcsjJlsx(json.get("ID") + "",
                        json.get("PERSONNAME") + "",
                        json.get("IDCARDTYPENUM") + "",
                        json.get("IDCARD18") + "",
                        json.get("CORPNAME") + "",
                        json.get("CORPCODE") + "",
                        json.get("SPECIALTYTYPNUM") + "",
                        json.get("PRJNUM") + "",
                        json.get("PRJNAME") + "",
                        json.get("ADDRESS") + "",
                        json.get("BUILDCORPNAME") + "",
                        json.get("BUILDCORPCODE") + "",
                        json.get("CREDITCLASSNUM") + "",
                        json.get("CREDITTYPE") + "",
                        json.get("CREDITCODE") + "",
                        json.get("CONTENT") + "",
                        json.get("HAPPENDATE") + "",
                        json.get("PROVINCENUM") + "",
                        json.get("CITYNUM") + "",
                        json.get("COUNTYNUM") + "",
                        json.get("PADEPTNAME") + "",
                        json.get("DEPARTTYPE") + "",
                        json.get("PUNISHEVIDENCE") + "",
                        json.get("FINALNUMBER") + "",
                        json.get("PADATE") + "",
                        json.get("PUNISHEDATE") + "",
                        json.get("PUNISHMONEY") + "",
                        json.get("DEPARTNAME") + "",
                        json.get("USERNAME") + "",
                        json.get("CREATEDATE") + "",
                        json.get("REPDEPTPRO") + "",
                        json.get("REPDEPTCITY") + "",
                        json.get("REPDEPTAREA") + "",
                        json.get("GOOGBADDIST") + "",
                        json.get("LOCAL") + "",
                        json.get("DEPTID") + "",
                        json.get("PACONTENT") + "",
                        json.get("ORDERCODE") + "",
                        json.get("BUSSTATUS") + "",
                        json.get("COMTIME") + "",
                        json.get("BEHAVIOR") + "",
                        YYYYMMDDHHMMSS.parse(json.get("UPDATIME") + ""));
                kcsjJlsxRepository.save(kcsjJlsx);
            }
        }
        return true;
    }

}
